package com.telecom.restaurant.service;

import com.telecom.restaurant.constant.DataResultConstant;
import com.telecom.restaurant.constant.DefaultConstant;
import com.telecom.restaurant.dao.CustomerDao;
import com.telecom.restaurant.dao.CustomerRestaurantChoiceDao;
import com.telecom.restaurant.exception.BizException;
import com.telecom.restaurant.model.CustomerPO;
import com.telecom.restaurant.model.CustomerRestaurantChoicePO;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * Created by qiqi on 2019/12/21.
 */
@Service
public class CustomerService {

    @Autowired
    private CustomerDao customerDao;

    @Autowired
    private WxService wxService;

    @Autowired
    private CustomerRestaurantChoiceDao customerRestaurantChoiceDao;

    public Long getUserChooseRestaurant(Long userId) {

        CustomerRestaurantChoicePO customerRestaurantChoicePO = customerRestaurantChoiceDao.selectByUserId(userId);
        if (customerRestaurantChoicePO == null) {
            return DefaultConstant.DEFAULT_RES_ID;
        }
        return customerRestaurantChoicePO.getRestaurantId();
    }

    public CustomerPO getOrCreateCustomer(String code) throws BizException {

        String userId = wxService.getUserId(code, 0);
        if (StringUtils.isBlank(userId)) {
            throw new BizException(DataResultConstant.WX_ERROR);
        }

        CustomerPO customerPO = customerDao.getByMobileOrUserId(null, userId);
        if (customerPO == null) {

            String mobile = wxService.getMobile(userId, 0);
            if (StringUtils.isBlank(mobile)) {
                throw new BizException(DataResultConstant.WX_ERROR);
            }
            customerPO = new CustomerPO();
            customerPO.setMobile(mobile);
            customerPO.setWxUserId(userId);

            customerDao.insert(customerPO);
        }

        return customerPO;
    }

}
